// pages/scanPDF/scanPDF.js
// const pdfjsLib = require('../../utils/pdf.js'); // 引入pdf.js
// const jsQR = require('../../utils/jsQR.js'); // 引入jsQR

Page({
  data: {
    qrContent: '', // 二维码内容
  },

  // 点击按钮下载并解析PDF文件
  async getPDFandRecognizeQRCode() {
    const pdfUrl = 'https://developer.qlist.cn/idrm/wxapi/demo/invoice/pdf';

    // 下载PDF文件
    wx.downloadFile({
      url: pdfUrl,
      success: (res) => {
        const filePath = res.tempFilePath;
        console.log(filePath);
        // this.extractQRCodeFromPDF(filePath);
      },
      fail: (err) => {
        console.error('下载PDF文件失败:', err);
      }
    });
  },

  // 从PDF中提取二维码
  extractQRCodeFromPDF(filePath) {
    const that = this;

    wx.getFileSystemManager().readFile({
      filePath,
      success: (res) => {
        const arrayBuffer = res.data;

        pdfjsLib.getDocument({
          data: arrayBuffer
        }).promise.then(function (pdfDoc) {
          // 逐页解析PDF文件
          const numPages = pdfDoc.numPages;
          for (let pageNum = 1; pageNum <= numPages; pageNum++) {
            pdfDoc.getPage(pageNum).then(function (page) {
              const viewport = page.getViewport({
                scale: 1.0
              });

              // 使用canvas绘制页面
              const canvas = wx.createCanvasContext('pdfCanvas');
              canvas.width = viewport.width;
              canvas.height = viewport.height;

              const renderContext = {
                canvasContext: canvas,
                viewport: viewport
              };

              page.render(renderContext).promise.then(() => {
                // 提取canvas上的二维码
                wx.canvasGetImageData({
                  canvasId: 'pdfCanvas',
                  x: 0,
                  y: 0,
                  width: canvas.width,
                  height: canvas.height,
                  success(res) {
                    const code = jsQR(res.data, res.width, res.height);
                    if (code) {
                      const qrData = that.extractDataFromQRCode(code.data);
                      that.setData({
                        qrContent: qrData
                      });
                    }
                  },
                  fail(err) {
                    console.error('提取二维码失败:', err);
                  }
                });
              });
            });
          }
        });
      },
      fail: (err) => {
        console.error('读取PDF文件失败:', err);
      }
    });
  },

  // 从二维码内容中提取金额和时间
  extractDataFromQRCode(qrData) {
    // 假设二维码内容是包含JSON数据，例如：{ "amount": 100, "date": "2024-10-10" }
    try {
      const data = JSON.parse(qrData);
      return `金额: ${data.amount}, 日期: ${data.date}`;
    } catch (err) {
      console.error('二维码数据解析失败:', err);
      return '无法解析二维码内容';
    }
  }
});